<?php
/*
 * 订单逻辑主控器
 */

namespace Home\Controller;


class BaseOrderController extends HomeController
{

    private $_userId;

    public function __construct()
    {

        parent::__construct();
        $this->_userId = session("userId");
    }

    /**
     * 生成订单号
     * @return string
     */
    protected function getOrderId($addrId)
    {
        $str = "MUC";
        $str .= time();
        $str .= rand(1000, 9999);
        $str .= $addrId;
        return $str;
    }


    /**
     * 根据选择乘客页面传过来的基本星系获取详细星系
     * 选择乘客->[订单详情] ->支付
     * @param  $addrId int 车次的id
     * @param  $psrIds array 乘客ids数组
     * @param  $dicCode string 折扣码
     *       $psrIds = $_POST['psr'];
     *       $dicCode = $_POST['dicCode'];
     * $psrIds  array
     */
    protected function getOrderDetail($addrInfo)
    {
        //乘客数组
        $psrIds = I('post.psr');


        //乘客数量
        $psrNum = count($psrIds);


        //根据折扣code获取折扣id
        $dicCode = I('post.dicCode');
        $discountInfo = M('discount')->where(array('dc_code' => $dicCode))->find();


        $totalPrice = $this->getTotalPrice($psrNum, $addrInfo['addr_price'], $addrInfo['addr_insur']);
        //保存到数据库的信息
        $dbData = array(

            'user_id' => $this->_userId,
            'od_name' => $this->getOrderId($addrInfo['addr_id']),
            'od_creat_time' => time(),
            'od_finish_time' => '0',
            'od_ticket_num' => $psrNum,
            "od_total_price" => $totalPrice,
            'od_sell_price' => $this->getSellPrice($discountInfo, $totalPrice),
            'od_status' => '0',
            'od_psr_ids' => $this->getPsrIds($psrIds),
            'od_addr_id' => $addrInfo['addr_id'],
            'od_insur_price' => $this->getInsurPrice($psrNum, $addrInfo['addr_insur']),
            'od_discount_id' => $discountInfo['dc_id'] ? $discountInfo['dc_id'] : '0',
            'od_get_ticket_person' => I('post.get_ticket_pseson'),
            'od_get_ticket_person_tel' => I('post.get_ticket_tel'),
            'od_pay_status' => '0',

        );
        return $dbData;
    }


    /**
     * 根据订单表的订单获取订单详情
     * @param $order array 订单基本信息数组
     * @param $addrInfo array 地址信息
     * @return mixed
     */
    protected function todetailOrder($order, $addrInfo)
    {
        //乘客信息
        $order['psrInfo'] = $this->getPsrInfoByPsrIds($order['od_psr_ids']);

        //单票价
        $order['unitPrice'] = $addrInfo['addr_price'];

        //出发地,目的地,时间
        $order['from'] = $addrInfo['addr_from'];
        $order['to'] = $addrInfo['addr_to'];
        $order['depart_time'] = $this->getFormateDateFromTimestamp($addrInfo['addr_depart_time']);
        return $order;
    }


    /**
     * 检查乘客信息是否合法
     * @param array $array 需要检验的数组
     */
    protected function checkPassengerInfo($data = array())
    {

        if (strlen($data['passengerName']) < 2) {
            return "姓名错误";
        }

        if (strlen($data['passengerTel']) != 11) {
            return "电话信息错误";
        }

        if (strlen($data['passengerIdCard']) < 18) {
            return "身份证信息错误";
        }
        return true;
    }


    /**
     * 获取总价
     * @param $psrNum int 乘客人数
     * @param $ticketPrice int 票价
     * @param $insurPrice int 保险价
     * @return mixed 总价
     */
    protected function getTotalPrice($psrNum, $ticketPrice, $insurPrice)
    {

        return ($ticketPrice + $insurPrice) * $psrNum;

    }


    /**
     * 获取保险价格
     * @return bool
     */
    protected function getInsurPrice($psrNum, $insurPrice)
    {
        return $psrNum * $insurPrice;
    }


    /**
     * 折后价
     * @param $discountInfo array 折扣数组
     * @param $totalPrice int 总 价
     * @param int $psrNum 乘客数量
     * @return float
     */
    protected function getSellPrice($discountInfo, $totalPrice, $psrNum = 0)
    {

        if (C('HOME_DEBUG')) {
            dump($discountInfo);
            dump($totalPrice);

        }
        //根据折扣打折
        if ($discountInfo['dc_type'] == '1') {
            $sellPrice = $totalPrice - $discountInfo['dc_money'];
        } else if ($discountInfo['dc_type'] == '2') {
            $sellPrice = $totalPrice * $discountInfo['dc_percent'] * 0.1;
        } else {
            //没有优惠券
            $sellPrice = $totalPrice;
        }
        //保险价格处理
        return $sellPrice;
    }


    /**
     * 获取乘车人的ids
     * @return string 1,2,3
     */
    protected function getPsrIds($data)
    {
        return rtrim(implode(',', $data), ',');

    }


    /**
     * 检查是否能提交购票信息
     * @param $data
     * @return string 错误信息
     */
    protected function checkDataIsLeague($data)
    {
        if ($data['user_id'] < 0) return "获取用户认证信息错误";
        if (empty($data['od_name'])) return "生产订单号错误";
        if ($data['od_ticket_num'] <= 0) return "未选择乘车人";
        if ($data['od_total_price'] <= 0) return "计算总价信息出错";
        if ($data['od_sell_price'] <= 0) return "计算销售信息错误";
        if (empty($data['od_psr_ids'])) return "未选择乘车人";
        if (empty($data['od_get_ticket_person'])) return "未填写取票人姓名";
        if (empty($data['od_get_ticket_person_tel'])) return "未填写取票人电话";
        if ($data['od_pay_status']!=0) return "非法操作(-100)";
        if ($data['od_status']!=0) return "非法操作(-102)";
        return true;

    }


    /**
     * 根据地址id获取地址信息
     */
    protected function getAddrInfoById($addrId)
    {
        return M('addr')->find($addrId);
    }

    /**
     * 根据时间戳得到年月日 时间 星期 2017-07-16 00:00 星期日
     * @param $timestamp
     */
    protected function getFormateDateFromTimestamp($timestamp)
    {
        return date("Y-m-d H:i", $timestamp) . " " . changeNumberToweekday(date('w', $timestamp));
    }

    /**
     * 根据时间戳获得时间  2017-11-20 02:46 星期一
     * @param $timestamp int 时间戳
     * @return string  2017-11-20 02:46 星期一
     */
    protected function getDateTimeWeekByTimestamp($timestamp)
    {
        return date("Y-m-d H:i", $timestamp) . " " . changeNumberToweekday(date('w', $timestamp));
    }


    /**
     * 根据乘客ids获取乘客信息
     * @param $psrIds
     * @return mixed
     */
    protected function getPsrInfoByPsrIds($psrIds)
    {
        $bool = strpos($psrIds, ',');

        if ($bool === false) {//只有一个乘客
            $res = M('passenger')->where(array('psr_id' => $psrIds))->select();
        } else {//多个乘客
            $map['psr_id'] = array('in', $psrIds);
            $res = M('passenger')->where($map)->select();
        }
        return $res;
    }


    /**
     * 判断订单号是否存在
     * 判断方式:
     * 检查当前addrId(车次id)  和 乘客是否在数据库
     * @param $order array 订单数组
     * @return mixed 存在:返回订单id  不存在:NULL
     */
    protected function checkDBIsExistOrder($order)
    {
        $res=  M('order')->where(array(
            'od_addr_id' => $order['od_addr_id'],
            'od_psr_ids' => $order['od_psr_ids']
        ))->getField('od_id');
        return $res;
    }


    /**
     * 选择乘客页面
     * v1.0.0基本完善
     */
    public function selectPassenger()
    {
        $addrId = session('ticketId');
        /*添加用户填写的乘客信息*/
        if (!empty($_POST)) {

            //检查数据的合法性
            if (($errMsg = $this->checkPassengerInfo($_POST)) !== true) {
                $this->err($errMsg);
                exit;
            }
            $dbData = array(

                'user_id' => session('userId'),
                'psr_id_card' => I('post.passengerIdCard'),
                'psr_tel' => I('post.passengerTel'),
                'psr_name' => I('post.passengerName'),
                'psr_status' => '1',

            );
            /*检查是否存在该乘客的数据*/

            $res = M('passenger')->where(array('psr_id_card' => $dbData['psr_id_card']))->getField('psr_id');//有就返回具体值,没有就返回null
            /*判断乘客表是否有该信息
                有:更新
                没有:添加
            */

            if ($res) {//有
                $dbData['modify_time'] = time();
                $b = M('passenger')->where(array('psr_id' => $res))->save($dbData);
                if ($b === false) {//根性失败
                    $this->err("服务器繁忙，请稍后再试");
                    exit;
                }

                //todo 更新成功,此处未处理

            } else {
                $dbData['creat_time'] = time();
                $res = D('passenger')->add($dbData);
                if (!$res) {
                    $this->err("服务器繁忙，请稍后再试");
                    exit;
                }
            }

        }

        /*显示用户现在添加过的乘客*/
        $userId = session('userId');


        //获取乘客信息
        $_map = array("user_id" => $userId);
        $psrIds = D("passenger")->where($_map)->select();
        $this->assign("ticketId", $addrId);


        //获取乘客
        $this->assign("psrInfo", $psrIds);
        $this->display();
    }


    /**
     * 取消订单session订单
     * 临时订单
     */
    public function cancenTicket()
    {
        $dbData = session('order');
        $dbData['od_status'] = 2;

        if ($this->checkDataIsLeague($dbData) === true) {
            M('order')->add($dbData);
        }
        session('order', null);
        session('orTider', null);

        $this->redirect('Ticket/ticketQueryResult');
    }


    /**
     * 根据id支付
     * @param $id
     */
    public function payOrderById($id)
    {
        $order = M('order')->find($id);
        $order = $this->detailOrder($order);
        $this->assign("order", $order);
        $this->display();
    }


    /**
     * 订单详情
     * @param $id
     */
    public function orderDetail($id)
    {
        $order = M('order')->find($id);
        $order = $this->detailOrder($order);
        $this->assign("order", $order);
        $this->display();
    }


    /**
     * 取消订单
     * 我的订单->未付款->取消订单
     * @param string $id 订单id
     */
    public function cancelHadNoPayTicket($id = '')
    {
        if (M('order')->where("od_id=$id")->setField('od_status', 2)) {
            $this->ok('取消成功');
        }

    }





}